<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Method解读, Swift, iOS, Python">
    <meta name="description" content="群组欢迎加入群组,闲聊工作&amp;amp;技术&amp;amp;问题等

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们知道iOS程序的入口函数在main.其实mian只是苹果给我们的”直观能够感受”">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Method解读 | waitwalker</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<!--导航-->

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    <!---->
                    <!--<img src="/medias/logo.png" class="logo-img" alt="LOGO">-->
                    <!---->
                    <span class="logo-span">waitwalker</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">waitwalker</div>
        <div class="logo-desc">
            
            Life is measured by thought and action not by time.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/waitwalker" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/waitwalker" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="https://github.com/waitwalker" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/7.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Method解读
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Runtime/" target="_blank">
                                <span class="chip bg-color">Runtime</span>
                            </a>
                        
                            <a href="/tags/底层/" target="_blank">
                                <span class="chip bg-color">底层</span>
                            </a>
                        
                            <a href="/tags/源码/" target="_blank">
                                <span class="chip bg-color">源码</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                Runtime源码解读
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-12
                </div>

                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>群组</strong><br><strong>欢迎加入群组,闲聊工作&amp;技术&amp;问题等</strong></p>
<p><img src="https://github.com/waitwalker/Resources/blob/master/Flutter/group/flutter_development_0923.JPG?raw=true" width="350" height="480" align="center"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我们知道iOS程序的入口函数在main.其实mian只是苹果给我们的”直观能够感受”的入口,在执行main之前,编译器已经帮我们做了相当多的事情.具体可以参考objc-os.h文件.Objective-C的Runtime库也是在main之前创建好的.我们关注sel_init()</p>
<h3 id="SEL"><a href="#SEL" class="headerlink" title="SEL:"></a>SEL:</h3><pre><code>/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;

    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&amp;map_images, load_images, unmap_image);
}
</code></pre><p>接口我们可以到sel_init()调用栈:</p>
<pre><code>_|   _objc_init()
  _|   _dyld_objc_notify_register
    _|    map_images_nolock()
       _|   sel_init()
</code></pre><p>在map_images_nolock()方法中我们看到在sel_init()下面有arr_init():</p>
<pre><code>void arr_init(void)
{
    AutoreleasePoolPage::init();
    SideTableInit();
}
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这个函数就是我们熟悉的AutoreleasePoolPage的初始化和全局SideTable的初始化,这个以后再分析.这里我们看一下sel_init()所做的工作:</p>
<pre><code>/***********************************************************************
* sel_init
* Initialize selector tables and register selectors used internally.
**********************************************************************/
void sel_init(size_t selrefCount)
{
    // save this value for later
    SelrefCount = selrefCount;

#if SUPPORT_PREOPT
    builtins = preoptimizedSelectors();

    if (PrintPreopt  &amp;&amp;  builtins) {
        uint32_t occupied = builtins-&gt;occupied;
        uint32_t capacity = builtins-&gt;capacity;

        _objc_inform(&quot;PREOPTIMIZATION: using selopt at %p&quot;, builtins);
        _objc_inform(&quot;PREOPTIMIZATION: %u selectors&quot;, occupied);
        _objc_inform(&quot;PREOPTIMIZATION: %u/%u (%u%%) hash table occupancy&quot;,
                     occupied, capacity,
                     (unsigned)(occupied/(double)capacity*100));
        }
#endif

    // Register selectors used by libobjc

#define s(x) SEL_##x = sel_registerNameNoLock(#x, NO)
#define t(x,y) SEL_##y = sel_registerNameNoLock(#x, NO)

    mutex_locker_t lock(selLock);

    s(load);
    s(initialize);
    t(resolveInstanceMethod:, resolveInstanceMethod);
    t(resolveClassMethod:, resolveClassMethod);
    t(.cxx_construct, cxx_construct);
    t(.cxx_destruct, cxx_destruct);
    s(retain);
    s(release);
    s(autorelease);
    s(retainCount);
    s(alloc);
    t(allocWithZone:, allocWithZone);
    s(dealloc);
    s(copy);
    s(new);
    t(forwardInvocation:, forwardInvocation);
    t(_tryRetain, tryRetain);
    t(_isDeallocating, isDeallocating);
    s(retainWeakReference);
    s(allowsWeakReference);

#undef s
#undef t
}
</code></pre><p>我们可以看到一些常见系统内置方法分别调用__sel_registerName()这个方法:</p>
<pre><code>static SEL __sel_registerName(const char *name, bool shouldLock, bool copy)
{
    SEL result = 0;

    if (shouldLock) selLock.assertUnlocked();
    else selLock.assertLocked();

    if (!name) return (SEL)0;

    result = search_builtins(name);
    if (result) return result;

    conditional_mutex_locker_t lock(selLock, shouldLock);
    if (namedSelectors) {
        result = (SEL)NXMapGet(namedSelectors, name);
    }
    if (result) return result;

    // No match. Insert.

    if (!namedSelectors) {
        namedSelectors = NXCreateMapTable(NXStrValueMapPrototype,
                                          (unsigned)SelrefCount);
    }
    if (!result) {
        // 初始化sel_alloc
        result = sel_alloc(name, copy);

        // 将selector 插入到NXMapTable 表中
        // fixme choose a better container (hash not map for starters)
        NXMapInsert(namedSelectors, sel_getName(result), result);
    }

    return result;
}
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这方法的作用是将selector注册到NXMapTable表中,如果selector不存在则调用selector初始化方法,然后将selector作为selector作为key,selector作为value存到NXMapTable哈希表中:</p>
<pre><code>static SEL sel_alloc(const char *name, bool copy)
{
    selLock.assertLocked();
    return (SEL)(copy ? strdupIfMutable(name) : name);
}
</code></pre><p>在objc.h文件中我们可以看到SEL的声明:</p>
<pre><code>/// An opaque type that represents a method selector.
typedef struct objc_selector *SEL;
</code></pre><p>至此我们可以理解了,SEL就是一个表示方法的selector指针,映射方法的名字.</p>
<h3 id="IMP"><a href="#IMP" class="headerlink" title="IMP:"></a>IMP:</h3><pre><code>/// A pointer to the function of a method implementation.
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ );
#else
typedef id _Nullable (*IMP)(id _Nonnull, SEL _Nonnull, ...);
#endif
</code></pre><p>从定义来看,IMP是一个指向实现函数的<strong>指针</strong>.IMP也是实现函数的入口,其和SEL的关系等以后将消息发送在细说.</p>
<h3 id="Method"><a href="#Method" class="headerlink" title="Method:"></a>Method:</h3><p>method的声明结构:</p>
<pre><code>typedef struct method_t *Method;
</code></pre><p>继续查看method_t的定义:</p>
<pre><code>struct method_t {
    SEL name;
    const char *types;
    MethodListIMP imp;

    struct SortBySELAddress :
        public std::binary_function&lt;const method_t&amp;,
                                    const method_t&amp;, bool&gt;
    {
        bool operator() (const method_t&amp; lhs,
                         const method_t&amp; rhs)
        { return lhs.name &lt; rhs.name; }
    };
};
</code></pre><p>method_t中有两个我们熟悉的成员变量:SEL和MethodListIMP,看一下MethodListIMP:</p>
<pre><code>#if __has_feature(ptrauth_calls)

// Method lists use process-independent signature for compatibility.
// Method caches use process-dependent signature for extra protection.
//   (fixme not yet __ptrauth(...) because of `stp` inline asm in objc-cache.mm)
using MethodListIMP = IMP __ptrauth_objc_method_list_imp;
using MethodCacheIMP =
    StorageSignedFunctionPointer&lt;IMP, ptrauth_key_process_dependent_code&gt;;

#else

using MethodListIMP = IMP;
using MethodCacheIMP = IMP;

#endif
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MethodListIMP其实就是IMP,method可以理解为SEL(方法名称)和IMP(方法实现)相互对应的集合体.正常的情况一个SEL对应一个IMP,而SEL和IMP的绑定到运行时才确定的.</p>
<h3 id="相关API"><a href="#相关API" class="headerlink" title="相关API"></a>相关API</h3><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;下面是NSObject.h和runtime.h文件为我们提供的有关SEL,IMP和Method相关的接口及说明:</p>
<h4 id="runtime-h文件"><a href="#runtime-h文件" class="headerlink" title="runtime.h文件:"></a>runtime.h文件:</h4><h5 id="根据SEL获取实例Method指针"><a href="#根据SEL获取实例Method指针" class="headerlink" title="根据SEL获取实例Method指针"></a>根据SEL获取实例Method指针</h5><pre><code>// 获取Method声明
OBJC_EXPORT Method _Nullable
class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

// 获取Method实现
/***********************************************************************
* class_getInstanceMethod.  Return the instance method for the
* specified class and selector.
**********************************************************************/
Method class_getInstanceMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    // This deliberately avoids +initialize because it historically did so.

    // This implementation is a bit weird because it&#39;s the only place that
    // wants a Method instead of an IMP.

#warning fixme build and search caches

    // Search method lists, try method resolver, etc.
    lookUpImpOrNil(cls, sel, nil,
                   NO/*initialize*/, NO/*cache*/, YES/*resolver*/);

#warning fixme build and search caches

    return _class_getMethod(cls, sel);
}
</code></pre><p>这里面调用了_class_getMethod()私有函数:</p>
<pre><code>/***********************************************************************
* _class_getMethod
* fixme
* Locking: read-locks runtimeLock
**********************************************************************/
static Method _class_getMethod(Class cls, SEL sel)
{
    mutex_locker_t lock(runtimeLock);
    return getMethod_nolock(cls, sel);
}

/***********************************************************************
* getMethod_nolock
* fixme
* Locking: runtimeLock must be read- or write-locked by the caller
**********************************************************************/
static method_t *
getMethod_nolock(Class cls, SEL sel)
{
    method_t *m = nil;

    runtimeLock.assertLocked();

    // fixme nil cls?
    // fixme nil sel?

    assert(cls-&gt;isRealized());

    while (cls  &amp;&amp;  ((m = getMethodNoSuper_nolock(cls, sel))) == nil) {
        cls = cls-&gt;superclass;
    }

    return m;
}
</code></pre><p>这个函数内部调用的是getMethodNoSuper_nolock():</p>
<pre><code>static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    runtimeLock.assertLocked();

    assert(cls-&gt;isRealized());
    // fixme nil cls?
    // fixme nil sel?

    for (auto mlists = cls-&gt;data()-&gt;methods.beginLists(),
              end = cls-&gt;data()-&gt;methods.endLists();
         mlists != end;
         ++mlists)
    {
        method_t *m = search_method_list(*mlists, sel);
        if (m) return m;
    }

    return nil;
}
</code></pre><p>查找方法的过程是先从本class的方法列表中查看是否存在,不存再在看父类递归这个过程( cls = cls-&gt;superclass).这个我们在以后讲消息发送,转发时在细看.</p>
<h5 id="根据SEL获取类Method指针"><a href="#根据SEL获取类Method指针" class="headerlink" title="根据SEL获取类Method指针"></a>根据SEL获取类Method指针</h5><pre><code>OBJC_EXPORT Method _Nullable
class_getClassMethod(Class _Nullable cls, SEL _Nonnull name)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);
</code></pre><p>类对象的方法列表存放在元类中,所以获取类方法要去元类中查找,其在获取的时候参数已经指明元类:</p>
<pre><code>/***********************************************************************
* class_getClassMethod.  Return the class method for the specified
* class and selector.
**********************************************************************/
Method class_getClassMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;
    //这里cls获取的是元类
    return class_getInstanceMethod(cls-&gt;getMeta(), sel);
}
</code></pre><h5 id="返回一个函数的实现指针"><a href="#返回一个函数的实现指针" class="headerlink" title="返回一个函数的实现指针:"></a>返回一个函数的实现指针:</h5><pre><code>OBJC_EXPORT IMP _Nullable
class_getMethodImplementation(Class _Nullable cls, SEL _Nonnull name)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
</code></pre><p>其实现过程:</p>
<pre><code>IMP class_getMethodImplementation(Class cls, SEL sel)
{
    IMP imp;

    if (!cls  ||  !sel) return nil;

    imp = lookUpImpOrNil(cls, sel, nil,
                         YES/*initialize*/, YES/*cache*/, YES/*resolver*/);

    // Translate forwarding function to C-callable external version
    if (!imp) {
        return _objc_msgForward;
    }

    return imp;
}
</code></pre><p>其内部我们可以看到两个主要的调用函数:lookUpImpOrNil()和_objc_msgForward.前面函数是获取SEL对应的IMP,其实现过程如下:</p>
<pre><code>/***********************************************************************
* lookUpImpOrNil.
* Like lookUpImpOrForward, but returns nil instead of _objc_msgForward_impcache
**********************************************************************/
IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
                   bool initialize, bool cache, bool resolver)
{
    IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
    if (imp == _objc_msgForward_impcache) return nil;
    else return imp;
}

// MARK: - 获取imp,先从缓存中查找imp,如果存在直接返回imp.
/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup.
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known.
*   If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use
*   must be converted to _objc_msgForward or _objc_msgForward_stret.
*   If you don&#39;t want forwarding at all, use lookUpImpOrNil() instead.
**********************************************************************/
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    // runtimeLock is held during isRealized and isInitialized checking
    // to prevent races against concurrent realization.

    // runtimeLock is held during method search to make
    // method-lookup + cache-fill atomic with respect to method addition.
    // Otherwise, a category could be added but ignored indefinitely because
    // the cache was re-filled with the old value after the cache flush on
    // behalf of the category.

    runtimeLock.lock();
    checkIsKnownClass(cls);

    if (!cls-&gt;isRealized()) {
        realizeClass(cls);
    }

    if (initialize  &amp;&amp;  !cls-&gt;isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // If sel == initialize, _class_initialize will send +initialize and
        // then the messenger will send +initialize again after this
        // procedure finishes. Of course, if this is not being called
        // from the messenger then it won&#39;t happen. 2778172
    }


 retry:
    runtimeLock.assertLocked();

    // 从缓存中尝试查找IMP
    // Try this class&#39;s cache.

    imp = cache_getImp(cls, sel);
    if (imp) goto done;

    // 从本类的方法列表中尝试查找IMP
    // Try this class&#39;s method lists.
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth-&gt;imp, sel, inst, cls);
            imp = meth-&gt;imp;
            goto done;
        }
    }

    // 从父类的方法列表中尝试查找IMP
    // Try superclass caches and method lists.
    {
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls-&gt;superclass;
             curClass != nil;
             curClass = curClass-&gt;superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal(&quot;Memory corruption in class list.&quot;);
            }

            // Superclass cache.
            imp = cache_getImp(curClass, sel);
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don&#39;t cache yet; call method
                    // resolver for this class first.
                    break;
                }
            }

            // Superclass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                log_and_fill_cache(cls, meth-&gt;imp, sel, inst, curClass);
                imp = meth-&gt;imp;
                goto done;
            }
        }
    }

    // 如果以上过程都没有找到,尝试一次动态方法解析
    // No implementation found. Try method resolver once.

    if (resolver  &amp;&amp;  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // Don&#39;t cache the result; we don&#39;t hold the lock so it may have
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }

    // 如果方法解析也没有IMP,启动消息转发
    // No implementation found, and method resolver didn&#39;t help.
    // Use forwarding.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlock();

    return imp;
}

</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;根据SEL在缓存中如果没有找到IMP,则在本类的Method获取找IMP,如果没有找到去父类中查找.以上过程都没有找到IMP的话,启动一次方法解析,方法解析也没有IMP的话就启动消息转发.</p>
<h5 id="一个对象是否响应某个方法"><a href="#一个对象是否响应某个方法" class="headerlink" title="一个对象是否响应某个方法"></a>一个对象是否响应某个方法</h5><pre><code>// MARK: - 一个实例对象是否响应某个方法
/**
 * Returns a Boolean value that indicates whether instances of a class respond to a particular selector.
 *
 * @param cls The class you want to inspect.
 * @param sel A selector.
 *
 * @return \c YES if instances of the class respond to the selector, otherwise \c NO.
 *
 * @note You should usually use \c NSObject&#39;s \c respondsToSelector: or \c instancesRespondToSelector:
 *  methods instead of this function.
 */
OBJC_EXPORT BOOL
class_respondsToSelector(Class _Nullable cls, SEL _Nonnull sel)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 是否响应某个方法
BOOL class_respondsToSelector(Class cls, SEL sel)
{
    return class_respondsToSelector_inst(cls, sel, nil);
}

// MARK: - 是否响应某个方法,其内部是通过获取IMP是否存在来判断
// inst is an instance of cls or a subclass thereof, or nil if none is known.
// Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
{
    IMP imp;

    if (!sel  ||  !cls) return NO;

    // Avoids +initialize because it historically did so.
    // We&#39;re not returning a callable IMP anyway.
    imp = lookUpImpOrNil(cls, sel, inst,
                         NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
    return bool(imp);
}
</code></pre><p>其最终还是痛SEL是否有对应IMP来判断对象能否响应某个方法.</p>
<h5 id="获取一个类的方法列表"><a href="#获取一个类的方法列表" class="headerlink" title="获取一个类的方法列表"></a>获取一个类的方法列表</h5><pre><code>// MARK: - 获取一个类的方法列表
/**
 * Describes the instance methods implemented by a class.
 *
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array.
 *  If outCount is NULL, the length is not returned.
 *
 * @return An array of pointers of type Method describing the instance methods
 *  implemented by the class—any instance methods implemented by superclasses are not included.
 *  The array contains *outCount pointers followed by a NULL terminator. You must free the array with free().
 *
 *  If cls implements no instance methods, or cls is Nil, returns NULL and *outCount is 0.
 *
 * @note To get the class methods of a class, use \c class_copyMethodList(object_getClass(cls), &amp;count).
 * @note To get the implementations of methods that may be implemented by superclasses,
 *  use \c class_getInstanceMethod or \c class_getClassMethod.
 */
OBJC_EXPORT Method _Nonnull * _Nullable
class_copyMethodList(Class _Nullable cls, unsigned int * _Nullable outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取一个类所有实现的方法列表
/***********************************************************************
* class_copyMethodList
* fixme
* Locking: read-locks runtimeLock
**********************************************************************/
Method *
class_copyMethodList(Class cls, unsigned int *outCount)
{
    unsigned int count = 0;
    Method *result = nil;

    if (!cls) {
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);

    assert(cls-&gt;isRealized());

    count = cls-&gt;data()-&gt;methods.count();

    if (count &gt; 0) {
        result = (Method *)malloc((count + 1) * sizeof(Method));

        count = 0;
        for (auto&amp; meth : cls-&gt;data()-&gt;methods) {
            result[count++] = &amp;meth;
        }
        result[count] = nil;
    }

    if (outCount) *outCount = count;
    return result;
}
</code></pre><h5 id="获取一个方法名称"><a href="#获取一个方法名称" class="headerlink" title="获取一个方法名称"></a>获取一个方法名称</h5><pre><code>// MARK: - 获取一个方法名称
/**
 * Returns the name of a method.
 *
 * @param m The method to inspect.
 *
 * @return A pointer of type SEL.
 *
 * @note To get the method name as a C string, call \c sel_getName(method_getName(method)).
 */
OBJC_EXPORT SEL _Nonnull
method_getName(Method _Nonnull m)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取一个方法名称
/***********************************************************************
* method_getName
* Returns this method&#39;s selector.
* The method must not be nil.
* The method must already have been fixed-up.
* Locking: none
**********************************************************************/
SEL
method_getName(Method m)
{
    if (!m) return nil;

    assert(m-&gt;name == sel_registerName(sel_getName(m-&gt;name)));
    return m-&gt;name;
}
</code></pre><p>获取一个方法名字最终还是通过sel_registerName()来获取,也是我们最开始的部分sel_init()提到.</p>
<h5 id="获取一个方法的IMP"><a href="#获取一个方法的IMP" class="headerlink" title="获取一个方法的IMP"></a>获取一个方法的IMP</h5><pre><code>// MARK: - 获取一个方法的实现
/**
 * Returns the implementation of a method.
 *
 * @param m The method to inspect.
 *
 * @return A function pointer of type IMP.
 */
OBJC_EXPORT IMP _Nonnull
method_getImplementation(Method _Nonnull m)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取一个方法的IMP
IMP
method_getImplementation(Method m)
{
    return m ? m-&gt;imp : nil;
}
</code></pre><p>通过直接Method中的imp成员变量</p>
<h5 id="获取一个方法的参数和返回值类型"><a href="#获取一个方法的参数和返回值类型" class="headerlink" title="获取一个方法的参数和返回值类型"></a>获取一个方法的参数和返回值类型</h5><pre><code>// MARK: - 获取一个方法的参数和返回值类型
/**
 * Returns a string describing a method&#39;s parameter and return types.
 *
 * @param m The method to inspect.
 *
 * @return A C string. The string may be \c NULL.
 */
OBJC_EXPORT const char * _Nullable
method_getTypeEncoding(Method _Nonnull m)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取一个方法的参数和返回值类型
/***********************************************************************
* method_getTypeEncoding
* Returns this method&#39;s old-style type encoding string.
* The method must not be nil.
* Locking: none
**********************************************************************/
const char *
method_getTypeEncoding(Method m)
{
    if (!m) return nil;
    return m-&gt;types;
}
</code></pre><h5 id="获取一个方法的参数数量"><a href="#获取一个方法的参数数量" class="headerlink" title="获取一个方法的参数数量"></a>获取一个方法的参数数量</h5><pre><code>// MARK: - 获取一个方法参数数量
/**
 * Returns the number of arguments accepted by a method.
 *
 * @param m A pointer to a \c Method data structure. Pass the method in question.
 *
 * @return An integer containing the number of arguments accepted by the given method.
 */
OBJC_EXPORT unsigned int
method_getNumberOfArguments(Method _Nonnull m)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取一个方法的参数数量
/***********************************************************************
* method_getNumberOfArguments.
**********************************************************************/
unsigned int method_getNumberOfArguments(Method m)
{
    if (!m) return 0;
    return encoding_getNumberOfArguments(method_getTypeEncoding(m));
}
</code></pre><h5 id="获取一个方法的返回值类型"><a href="#获取一个方法的返回值类型" class="headerlink" title="获取一个方法的返回值类型"></a>获取一个方法的返回值类型</h5><pre><code>// MARK: - 获取一个方法的返回值类型
/**
 * Returns a string describing a method&#39;s return type.
 *
 * @param m The method to inspect.
 *
 * @return A C string describing the return type. You must free the string with \c free().
 */
OBJC_EXPORT char * _Nonnull
method_copyReturnType(Method _Nonnull m)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取方法的返回值类型
char * method_copyReturnType(Method m)
{
    return encoding_copyReturnType(method_getTypeEncoding(m));
}
</code></pre><h5 id="获取方法某个参数的类型"><a href="#获取方法某个参数的类型" class="headerlink" title="获取方法某个参数的类型"></a>获取方法某个参数的类型</h5><pre><code>// MARK: - 获取方法某个参数的类型
/**
 * Returns a string describing a single parameter type of a method.
 *
 * @param m The method to inspect.
 * @param index The index of the parameter to inspect.
 *
 * @return A C string describing the type of the parameter at index \e index, or \c NULL
 *  if method has no parameter index \e index. You must free the string with \c free().
 */
OBJC_EXPORT char * _Nullable
method_copyArgumentType(Method _Nonnull m, unsigned int index)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取方法某个参数类型
char * method_copyArgumentType(Method m, unsigned int index)
{
    return encoding_copyArgumentType(method_getTypeEncoding(m), index);
}
</code></pre><h5 id="获取方法返回值类型"><a href="#获取方法返回值类型" class="headerlink" title="获取方法返回值类型"></a>获取方法返回值类型</h5><pre><code>// MARK: - 获取方法返回值类型
/**
 * Returns by reference a string describing a method&#39;s return type.
 *
 * @param m The method you want to inquire about.
 * @param dst The reference string to store the description.
 * @param dst_len The maximum number of characters that can be stored in \e dst.
 *
 * @note The method&#39;s return type string is copied to \e dst.
 *  \e dst is filled as if \c strncpy(dst, parameter_type, dst_len) were called.
 */
OBJC_EXPORT void
method_getReturnType(Method _Nonnull m, char * _Nonnull dst, size_t dst_len)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 获取方法返回值类型
void method_getReturnType(Method m, char *dst, size_t dst_len)
{
    encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
}
</code></pre><h5 id="更新设置某个方法的IMP"><a href="#更新设置某个方法的IMP" class="headerlink" title="更新设置某个方法的IMP"></a>更新设置某个方法的IMP</h5><pre><code>// MARK: - 更新设置某个方法的IMP
/**
 * Sets the implementation of a method.
 *
 * @param m The method for which to set an implementation.
 * @param imp The implemention to set to this method.
 *
 * @return The previous implementation of the method.
 */
OBJC_EXPORT IMP _Nonnull
method_setImplementation(Method _Nonnull m, IMP _Nonnull imp)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 更新设置某个方法IMP
IMP
method_setImplementation(Method m, IMP imp)
{
    // Don&#39;t know the class - will be slow if RR/AWZ are affected
    // fixme build list of classes whose Methods are known externally?
    mutex_locker_t lock(runtimeLock);
    return _method_setImplementation(Nil, m, imp);
}

// MARK: - 更新设置某个方法的IMP
/***********************************************************************
* method_setImplementation
* Sets this method&#39;s implementation to imp.
* The previous implementation is returned.
**********************************************************************/
static IMP
_method_setImplementation(Class cls, method_t *m, IMP imp)
{
    runtimeLock.assertLocked();

    if (!m) return nil;
    if (!imp) return nil;

    IMP old = m-&gt;imp;
    m-&gt;imp = imp;

    // Cache updates are slow if cls is nil (i.e. unknown)
    // RR/AWZ updates are slow if cls is nil (i.e. unknown)
    // fixme build list of classes whose Methods are known externally?

    flushCaches(cls);

    updateCustomRR_AWZ(cls, m);

    return old;
}
</code></pre><p>先找到old imp,然后把old imp 替换成 new imp.</p>
<h5 id="交换两个方法的实现即交换两个方法的IMP"><a href="#交换两个方法的实现即交换两个方法的IMP" class="headerlink" title="交换两个方法的实现即交换两个方法的IMP"></a>交换两个方法的实现即交换两个方法的IMP</h5><pre><code>// MARK: - 交换两个方法的实现即交换两个方法的IMP
/**
 * Exchanges the implementations of two methods.
 *
 * @param m1 Method to exchange with second method.
 * @param m2 Method to exchange with first method.
 *
 * @note This is an atomic version of the following:
 *  \code
 *  IMP imp1 = method_getImplementation(m1);
 *  IMP imp2 = method_getImplementation(m2);
 *  method_setImplementation(m1, imp2);
 *  method_setImplementation(m2, imp1);
 *  \endcode
 */
OBJC_EXPORT void
method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 交换两个方法的实现即交换两个方法的IMP
void method_exchangeImplementations(Method m1, Method m2)
{
    if (!m1  ||  !m2) return;

    mutex_locker_t lock(runtimeLock);

    IMP m1_imp = m1-&gt;imp;
    m1-&gt;imp = m2-&gt;imp;
    m2-&gt;imp = m1_imp;


    // RR/AWZ updates are slow because class is unknown
    // Cache updates are slow because class is unknown
    // fixme build list of classes whose Methods are known externally?

    flushCaches(nil);

    updateCustomRR_AWZ(nil, m1);
    updateCustomRR_AWZ(nil, m2);
}
</code></pre><h4 id="NSObject-h文件"><a href="#NSObject-h文件" class="headerlink" title="NSObject.h文件"></a>NSObject.h文件</h4><h5 id="执行某个方法"><a href="#执行某个方法" class="headerlink" title="执行某个方法"></a>执行某个方法</h5><p>执行某个方法,一般用于方法解析中动态添加方法,下面这几个方法功能类似:</p>
<pre><code>// MARK: - 执行某个方法 一般用于方法解析中动态添加方法
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

// MARK: -  执行某个方法 一般用于方法解析中动态添加方法
- (id)performSelector:(SEL)sel {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL))objc_msgSend)(self, sel);
}

- (id)performSelector:(SEL)sel withObject:(id)obj {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
}

- (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
}
</code></pre><p>先判断这个方法是否存在doesNotRecognizeSelector(),不存在报错”unrecognized selector sent to instance”.然后调用了message.h中的消息发送函数.</p>
<h5 id="内省方法-是否响应某个方法"><a href="#内省方法-是否响应某个方法" class="headerlink" title="内省方法:是否响应某个方法"></a>内省方法:是否响应某个方法</h5><pre><code>// MARK: - 内省方法:是否响应某个方法
- (BOOL)respondsToSelector:(SEL)aSelector;

// MARK: - 是否响应某个方法
- (BOOL)respondsToSelector:(SEL)sel {
    if (!sel) return NO;
    return class_respondsToSelector_inst([self class], sel, self);
}

// MARK: - 是否响应某个方法,其内部是通过获取IMP是否存在来判断
// inst is an instance of cls or a subclass thereof, or nil if none is known.
// Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
{
    IMP imp;

    if (!sel  ||  !cls) return NO;

    // Avoids +initialize because it historically did so.
    // We&#39;re not returning a callable IMP anyway.
    imp = lookUpImpOrNil(cls, sel, inst,
                         NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
    return bool(imp);
}
</code></pre><h5 id="一个实例对象是否响应某个方法"><a href="#一个实例对象是否响应某个方法" class="headerlink" title="一个实例对象是否响应某个方法"></a>一个实例对象是否响应某个方法</h5><pre><code>// MARK: - 一个对象是否响应某个方法
+ (BOOL)instancesRespondToSelector:(SEL)aSelector;

// MARK: - 一个对象是否响应某个方法
+ (BOOL)instancesRespondToSelector:(SEL)sel {
    if (!sel) return NO;
    return class_respondsToSelector(self, sel);
}
</code></pre><h5 id="获取一个SEL对应的IMP"><a href="#获取一个SEL对应的IMP" class="headerlink" title="获取一个SEL对应的IMP"></a>获取一个SEL对应的IMP</h5><pre><code>// MARK: - 获取一个SEL对应的IMP
- (IMP)methodForSelector:(SEL)aSelector;

// MARK: - 获取一个SEL对应的IMP
- (IMP)methodForSelector:(SEL)sel {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return object_getMethodImplementation(self, sel);
}
</code></pre><h5 id="获取一个实例方法SEL对应的IMP"><a href="#获取一个实例方法SEL对应的IMP" class="headerlink" title="获取一个实例方法SEL对应的IMP"></a>获取一个实例方法SEL对应的IMP</h5><pre><code>// MARK: - 获取一个实例方法SEL对应的IMP
+ (IMP)instanceMethodForSelector:(SEL)aSelector;

// MARK: - 获取一个实例方法SEL对应的IMP
+ (IMP)instanceMethodForSelector:(SEL)sel {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return class_getMethodImplementation(self, sel);
}
</code></pre><h5 id="不能响应某个SEL"><a href="#不能响应某个SEL" class="headerlink" title="不能响应某个SEL"></a>不能响应某个SEL</h5><pre><code>// MARK: - 不能响应某个SEL,报错
- (void)doesNotRecognizeSelector:(SEL)aSelector;

// MARK: - 不能响应某个方法
// Replaced by CF (throws an NSException)
- (void)doesNotRecognizeSelector:(SEL)sel {
    _objc_fatal(&quot;-[%s %s]: unrecognized selector sent to instance %p&quot;,
                object_getClassName(self), sel_getName(sel), self);
}
</code></pre><h5 id="动态方法解析"><a href="#动态方法解析" class="headerlink" title="动态方法解析"></a>动态方法解析</h5><p>动态方法解析,一般用来给某个没有实现的方法添加一个实现;返回false时,执行消息转发流程</p>
<pre><code>// MARK: - 动态方法解析
+ (BOOL)resolveClassMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
+ (BOOL)resolveInstanceMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// MARK: - 动态方法解析
+ (BOOL)resolveClassMethod:(SEL)sel {
    return NO;
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return NO;
}
</code></pre><h5 id="消息转发相关"><a href="#消息转发相关" class="headerlink" title="消息转发相关"></a>消息转发相关</h5><pre><code>// MARK: - 消息转发相关
- (id)forwardingTargetForSelector:(SEL)aSelector OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

- (void)forwardInvocation:(NSInvocation *)anInvocation OBJC_SWIFT_UNAVAILABLE(&quot;&quot;);
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector OBJC_SWIFT_UNAVAILABLE(&quot;&quot;);

+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector OBJC_SWIFT_UNAVAILABLE(&quot;&quot;);
</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;本文主要介绍了SEL,IMP,Method的定义和实现,以及系统为我们提供的常用API.这里面涉及到到向一个对象发送消息的流程及转发过程,这个会在以后的章节中讲到.<br></p>
<h3 id="编译后源码库"><a href="#编译后源码库" class="headerlink" title="编译后源码库"></a>编译后源码库</h3><p><strong>编译后的源码放在<a href="https://github.com/waitwalker/Runtime" target="_blank" rel="noopener">Github</a>, 如果对你有帮助,请给一个star吧!</strong></p>
<h3 id="博客地址-amp-相关文章"><a href="#博客地址-amp-相关文章" class="headerlink" title="博客地址&amp;相关文章"></a>博客地址&amp;相关文章</h3><p><strong>博客地址:</strong> <a href="https://waitwalker.github.io/">https://waitwalker.github.io/</a></p>
<p>系列文章:</p>
<p><a href="https://waitwalker.github.io/2019/04/08/Runtime%E6%BA%90%E7%A0%81%E7%BC%96%E8%AF%91/">1. Runtime源码编译</a></p>
<p><a href="https://waitwalker.github.io/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/">2. objc_object解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/12/Method%E8%A7%A3%E8%AF%BB/">3. Method解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Class%E8%A7%A3%E8%AF%BB/">4. Class解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Ivar-objc-property-t-Protocol%E8%A7%A3%E8%AF%BB/">5. Ivar objc_property_t Protocol解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/18/Block%E8%A7%A3%E8%AF%BB/">6. Block解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/22/Retain-Release解读/" target="_blank" rel="noopener">7. Retain&amp;Release解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/23/Autorelease解读/" target="_blank" rel="noopener">8. Autorelease解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/24/Weak解读/" target="_blank" rel="noopener">9. Weak解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/25/msgSend-解读/" target="_blank" rel="noopener">10. msgSend()解读</a></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            <div class="reprint">
                <p>
                    <span class="reprint-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="https://waitwalker.github.io" class="b-link-green">waitwalker</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/04/12/Method解读/" class="b-link-green">Method解读</a>
                </p>
            </div>
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/13/Bedrock-Privacy-Policy/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/12.jpg" class="responsive-img" alt="Bedrock Privacy Policy">
                        
                        <span class="card-title">Bedrock Privacy Policy</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">1.我们尊重用户的隐私并对非法窃取用户隐私的行为予以坚决抵制.
We respect user privacy and resist those who illegally steal user privacy.
2.Bedrock 仅收集</div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-13
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/隐私政策/" class="post-category" target="_blank">
                                    隐私政策
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Bedrock隐私政策/" target="_blank">
                        <span class="chip bg-color">Bedrock隐私政策</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/11/队列/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="队列">
                        
                        <span class="card-title">队列</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

像栈一样,队列(queue)也是表.队列的操作操两端进行,一端插入,一端删除.
队列的基本操作入队(Enqueue)操作入队是在队列的末尾插入元素.
出队(Dequeue)操作出队</div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-11
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/数据结构与算法/" class="post-category" target="_blank">
                                    数据结构与算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/数据结构/" target="_blank">
                        <span class="chip bg-color">数据结构</span>
                    </a>
                    
                    <a href="/tags/算法/" target="_blank">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/Swift/" target="_blank">
                        <span class="chip bg-color">Swift</span>
                    </a>
                    
                    <a href="/tags/队列/" target="_blank">
                        <span class="chip bg-color">队列</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: waitwalker<br />'
            + '作者: waitwalker<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站在原作者&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题基础上搭建.

            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis"><!---->
<a href="https://github.com/waitwalker" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
    <i class="fa fa-github"></i>
</a>

<a href="https://twitter.com/284485487" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-twitter"></i>
</a>

<a href="https://www.facebook.com/profile.php?id=100003684945279" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-facebook"></i>
</a>

<a href="https://t.me/joinchat/Ej0o0A1ntlq5ZFIMzzO5Pw" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-telegram"></i>
</a>

<a href="https://www.weibo.com/1789419613/profile?topnav=1&wvr=6&is_all=1" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-weibo"></i>
</a>


<!--原来-->
<!---->
    <!--<a href="mailto:waitwalker@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-envelope-open"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=284485487" class="tooltipped" data-tooltip="QQ联系我: 284485487" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-qq"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-rss"></i>-->
    <!--</a>-->
<!----></div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->




    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>